package org.xhy.hrm;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements RequestInterceptor{

    //Fiegn的请求模板
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //获取请求对象 旧线程 到 feign 会开启一个新的线程，但是新的线程中没有token！获取token设置到新线程
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();

        //获取请求头中的Authorization
        String authorization = request.getHeader("Authorization");

        //设置到新线程的请求头
        requestTemplate.header("Authorization",authorization);

        log.info("拦截器token:{}", authorization);
    }
}
